package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.entity.Course;
import com.pn.taikao.entity.StudentCourse;
import com.pn.taikao.entity.User;
import com.pn.taikao.service.CourseService;
import com.pn.taikao.service.StudentCourseService;
import com.pn.taikao.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/student-courses")
public class StudentCourseController {

    private final StudentCourseService studentCourseService;
    private final CourseService courseService;

    public StudentCourseController(StudentCourseService studentCourseService, CourseService courseService) {
        this.studentCourseService = studentCourseService;
        this.courseService = courseService;
    }

    /**
     * 学生选课
     */
    @PostMapping("/select/{courseId}")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Long> selectCourse(@PathVariable("courseId") Long courseId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        Long id = studentCourseService.selectCourse(currentUserId, courseId);
        return ApiResponse.success(id);
    }

    /**
     * 学生退课
     */
    @DeleteMapping("/unselect/{courseId}")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Void> unselectCourse(@PathVariable("courseId") Long courseId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        studentCourseService.unselectCourse(currentUserId, courseId);
        return ApiResponse.success(null);
    }

    /**
     * 查询学生是否已选该课程
     */
    @GetMapping("/check/{courseId}")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<Boolean> checkSelected(@PathVariable("courseId") Long courseId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        boolean selected = studentCourseService.isSelected(currentUserId, courseId);
        return ApiResponse.success(selected);
    }

    /**
     * 获取学生已选课程列表
     */
    @GetMapping("/my")
    @PreAuthorize("hasRole('STUDENT')")
    public ApiResponse<List<Course>> getMyCourses() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        List<StudentCourse> studentCourses = studentCourseService.getByStudentId(currentUserId);
        List<Long> courseIds = studentCourses.stream()
                .map(StudentCourse::getCourseId)
                .collect(Collectors.toList());
        
        List<Course> courses = courseIds.stream()
                .map(courseService::getById)
                .filter(course -> course != null)
                .collect(Collectors.toList());
        
        return ApiResponse.success(courses);
    }

    /**
     * 获取选择某课程的学生数量
     */
    @GetMapping("/course/{courseId}/count")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER')")
    public ApiResponse<Long> getCourseStudentCount(@PathVariable("courseId") Long courseId) {
        long count = studentCourseService.countByCourseId(courseId);
        return ApiResponse.success(count);
    }

    /**
     * 获取选择某课程的学生列表（教师和管理员可查看）
     */
    @GetMapping("/course/{courseId}/students")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER')")
    public ApiResponse<List<User>> getCourseStudents(@PathVariable("courseId") Long courseId) {
        // 检查课程是否存在
        Course course = courseService.getById(courseId);
        if (course == null) {
            return ApiResponse.error("课程不存在");
        }
        
        // 教师只能查看自己创建的课程的学生列表
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (!course.getTeacherId().equals(SecurityUtils.getCurrentUserId())) {
                return ApiResponse.error("无权限查看该课程的学生列表");
            }
        }
        
        List<User> students = studentCourseService.getStudentsByCourseId(courseId);
        return ApiResponse.success(students);
    }
}
